package com.source.app.selenium;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.source.app.rukuai.RuoKuai;
import com.source.utils.Utils;
import com.source.utils.train.RequestUtil;

public class CouponCenterAction {

	private final static String CouponCenterUrl = "https://coupon.m.jd.com/center/getCouponCenter.action";

	/**
	 * 提交订单
	 */
	private final static String receiveCouponUrl = "https://coupon.m.jd.com/center/receiveCoupon.json";

	private final static String image_path = "/Users/admin/images_/";

	
	//抢不到 循环次数
	private static final int COUNT = 5;

	private static String rukuai_username;

	private static String rukuai_password;

	private static String typeid;

	private static String softid;

	private static String softkey;

	private static String rukuai_timeout;

	static {
		rukuai_username = "";//若快账号
		rukuai_password = "";//若快密码
		typeid = "3040";
		softid = "1";
		softkey = "b40ffbee5c1cf4e38028c197eb2fc751";
		rukuai_timeout = "90";
	}

	public static void main(String[] args) {
		String cookies = LoginAction.login("京东账号", "京东密码");
		while (true) {
			if (Utils.isEmpty(cookies)) {
				return;
			}
			start(cookies);
		}
	}
	public static void start(String cookies) {
		if (Utils.isEmpty(cookies)) {
			return;
		}
		//查询优惠卷列表
		String couponlist = RequestCouponCenter(1, JDCode.SHLX.getCode(), cookies);
		JSONObject couponlistResult = JSONObject.parseObject(couponlist);
		JSONArray couponItems = couponlistResult.getJSONArray("couponItem");
		int totalCount = couponlistResult.getIntValue("totalCount");
		int page = totalCount/10 + 1;
		//循环提交每个优惠卷
		forSubmit(cookies, couponItems);
		if(page>1){
			
			for (int i = 2; i < page; i++) {
				System.out.println("当前页："+i);
				couponlistResult = JSONObject.parseObject(couponlist);
				couponlist = RequestCouponCenter(i, JDCode.SHLX.getCode(), cookies);
				 couponItems = couponlistResult.getJSONArray("couponItem");
				forSubmit(cookies, couponItems);
			}
		}
	}

	
	public static void forSubmit(String cookies,JSONArray couponItems){
		String couponId;
		String roleId;
		if (couponItems.size() <= 0) {
			return;
		}
		for (int i = 0; i < couponItems.size(); i++) {
			JSONObject couponItem = couponItems.getJSONObject(i);
			String limitStr =couponItem.getString("limitStr");
			if(!limitStr.contains("火车票")){
				continue;
			}
			String actId = couponItem.getString("key");
			int rate = couponItem.getIntValue("rate");
			if (rate >= 100) {
				continue;
			}
			couponId = couponItem.getString("id");
			roleId = couponItem.getString("roleId");
			//循环提交抢优惠卷
			for (int j = 0; j < COUNT; j++) {
				String codeKey = crateCodeKey(cookies, "6");
				//获取验证码的结果
				JSONObject captheCodeObject = getCaptheCode(cookies, codeKey);
				if (Utils.isEmpty(captheCodeObject)) {
					return;
				}
				String id = captheCodeObject.getString("id");
				String validateCode = captheCodeObject.getString("code");
				//提交获取响应结果
				String response = submit(cookies, validateCode, couponId, roleId, actId, codeKey, "5");
				if(response.contains("验证码错误")){
					RuoKuai.error(rukuai_username, rukuai_password, softid, softkey, id);
				}
				try {
					JSONObject resposeObject = JSONObject.parseObject(response);
					if(resposeObject.getString("isSuccess").equals("T")
							||resposeObject.getString("desc").contains("您今天已经参加过此活动")){
						break;
					}

				} catch (Exception e) {
				}
			}
			
			
			
		}
	}
	
	
	/**
	 * 提交抢卷
	 * 
	 * @param cookies
	 * @param validateCode
	 * @param couponId
	 * @param roleId
	 * @param actId
	 * @param codeKey
	 * @param takeRule
	 */
	public static String submit(String cookies, String validateCode, String couponId, String roleId, String actId,
			String codeKey, String takeRule) {
		String param = "couponId=" + couponId + "&roleId=" + roleId + "&actId=" + actId + "&codeKey=" + codeKey
				+ "&validateCode=" + validateCode + "&to=&takeRule=" + takeRule;
		String Referer = "https://coupon.m.jd.com/center/getCouponCenter.action";
		String ContentType = "application/x-www-form-urlencoded";
		String ContentLength = param.length() + "";
		Map<String, String> header = RequestUtil.getRequestHeader(cookies, Referer, ContentType, ContentLength, false,
				false, false);
		String respose = RequestUtil.post(receiveCouponUrl, param, RequestUtil.UTF8, header, 0, null);
		System.out.println(respose);
		return respose;
		

	}

	/**
	 * 获取验证码code
	 * 
	 * @param cookies
	 * @param codekey
	 * @return
	 */
	public static JSONObject getCaptheCode(String cookies, String codekey) {
		JSONObject res = new JSONObject();

		try {
			String captheUrl = "https://coupon.m.jd.com/authCode/authCodeImg.action?key=" + codekey + "&rand="
					+ new java.util.Random().nextInt(100000);
			Map<String, String> header = RequestUtil.getRequestHeader(cookies, null, null, null, false, false, false);
			URLConnection urlConnection = RequestUtil.getURLConnection(captheUrl, header, 0, null);
			InputStream inputStream = urlConnection.getInputStream();
			JSONObject xml = createByPost(rukuai_username, rukuai_password, typeid, rukuai_timeout, softid, softkey,
					inputStream);
			if (Utils.isEmpty(xml)) {
				return null;
			}
			byte[] data = xml.getBytes("data");
			BufferedImage originalImage = ImageIO.read(byte2Input(data));
			JSONObject jsonCode = displayXmlResult(xml.getString("result"));
			if (!Utils.isEmpty(jsonCode)) {
				boolean success = jsonCode.getBooleanValue("success");
				if (success) {
					String capthe = image_path + jsonCode.getString("result") + ".png";
					ImageIO.write(originalImage, "png", new File(capthe));
					res.put("code", jsonCode.getString("result"));
					res.put("id", jsonCode.getString("id"));
					return res;
				} else {
					RuoKuai.error(rukuai_username, rukuai_password, softid, softkey, jsonCode.getString("id"));
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	/**
	 * 若快打码
	 * 
	 * @param username
	 * @param password
	 * @param typeid
	 * @param timeout
	 * @param softid
	 * @param softkey
	 * @param inputStream
	 * @return
	 */
	public static JSONObject createByPost(String username, String password, String typeid, String timeout,
			String softid, String softkey, InputStream inputStream) {
		JSONObject res = new JSONObject();

		String param = String.format("username=%s&password=%s&typeid=%s&timeout=%s&softid=%s&softkey=%s", username,
				password, typeid, timeout, softid, softkey);
		try {
			byte[] data = input2byte(inputStream);
			if (data.length > 0) {
				String result = RuoKuai.httpPostImage("http://api.ruokuai.com/create.xml", param, data);
				res.put("result", result);
				res.put("data", data);
				return res;
			}
		} catch (Exception e) {
			res = null;
		}

		return null;
	}

	/**
	 * 解析若快返回的结果
	 * 
	 * @param xml
	 * @return
	 */
	public static JSONObject displayXmlResult(String xml) {
		JSONObject json = new JSONObject();
		if (xml.length() <= 0) {
			return null;
		} else {
			Document dm;
			try {
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				dm = db.parse(new ByteArrayInputStream(xml.getBytes("utf-8")));
				NodeList resultNl = dm.getElementsByTagName("Result");
				NodeList idNl = dm.getElementsByTagName("Id");
				NodeList errorNl = dm.getElementsByTagName("Error");
				if (resultNl.getLength() > 0) {
					if (idNl.getLength() > 0) {
						json.put("id", idNl.item(0).getFirstChild().getNodeValue());
						json.put("result", resultNl.item(0).getFirstChild().getNodeValue());
						json.put("success", true);
						return json;
					}
				} else if (errorNl.getLength() > 0) {
					json.put("id", idNl.item(0).getFirstChild().getNodeValue());
					json.put("error", errorNl.item(0).getFirstChild().getNodeValue());
					json.put("success", false);
					return json;
				} else {
					return null;
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 把byte[]转换为输入流
	 * 
	 * @param buf
	 * @return
	 */
	public static final InputStream byte2Input(byte[] buf) {
		return new ByteArrayInputStream(buf);
	}

	/**
	 * 输入流转换为byte[]
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	public static final byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	/**
	 * 创建codekey
	 * 
	 * @param cookies
	 * @param rute
	 * @return
	 */
	public static String crateCodeKey(String cookies, String rute) {
		try {
			String createCodeKeyUrl = "https://coupon.m.jd.com/authCode/createCodeKey.json";
			String param = "args=" + rute;
			String Referer = "https://coupon.m.jd.com/center/getCouponCenter.action";
			String ContentType = "application/x-www-form-urlencoded";
			String ContentLength = param.length() + "";
			Map<String, String> header = RequestUtil.getRequestHeader(cookies, Referer, ContentType, ContentLength,
					false, false, false);
			String codeKeyResult = RequestUtil.post(createCodeKeyUrl, param, RequestUtil.UTF8, header, 0, null);
			JSONObject cokeObject = JSONObject.parseObject(codeKeyResult);
			String codeKey = cokeObject.getString("codeKey");
			return codeKey;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取优惠卷列表
	 * 
	 * @param page
	 * @param categoryId
	 * @param cookies
	 * @return
	 */
	public static String RequestCouponCenter(int page, int categoryId, String cookies) {
		Map<String, String> header = RequestUtil.getRequestHeader(cookies, null, null, null, false, false, false);
		RequestUtil.get(CouponCenterUrl, RequestUtil.UTF8, header, 0, null);
		String toCouponListUrl = "https://coupon.m.jd.com/center/toCouponList.json?page=" + page + "&categoryId="
				+ categoryId;
		System.out.println(toCouponListUrl);
		return RequestUtil.get(toCouponListUrl, RequestUtil.UTF8, header, 0, null);
	}

}
